/*
 * Copyright 2010 Yannick Stucki (yannickstucki.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This class was built upon a class from an Android tutorial by Google Inc.
 * , also released under Apache 2.0 2008.
 */
package com.yannickstucki.android.musicqueue.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.yannickstucki.android.musicqueue.util.Logger;

/**
 * A simple database to store those songs which are starred.
 */
public class DbAdapter {

  /**
   * Name of the primary id field (renamed so Android will know where to bind
   * the tables id field).
   */
  public static final String KEY_ROWID = "_id";

  /**
   * A reference to the one instance of the inner class that helps create the
   * database.
   */
  private DatabaseHelper databaseHelper;

  /**
   * The actual database.
   */
  private SQLiteDatabase database;

  /**
   * Database creation sql statement.
   */
  private static final String DATABASE_CREATE = "create table " + "TABLE_NAME"
      + " (_id integer primary key autoincrement, " + "REPLACE" + ");";

  /**
   * The name of the database. There's only one.
   */
  private static final String DATABASE_NAME = "musicqueue";

  /**
   * The name of the table. There's only one.
   */
  public static final String TABLE_SONGS = "songs";

  /**
   * The version of the database. Increment this whenever the database format
   * changes so a new one is generated.
   */
  private static final int DATABASE_VERSION = 12;

  /**
   * Needed for opening the database.
   */
  private final Context context;

  /**
   * Inner class that actually creates the database.
   */
  private static class DatabaseHelper extends SQLiteOpenHelper {

    /**
     * A context is needed to create the database.
     */
    DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      String insertStr = "uniqueID text not null";
      String songCreate = DATABASE_CREATE.replace("REPLACE", insertStr);
      songCreate = songCreate.replace("TABLE_NAME", TABLE_SONGS);
      db.execSQL(songCreate);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      Logger.out("Upgrading database from version " + oldVersion + " to " + newVersion
          + ", which will destroy all old data");
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_SONGS);
      onCreate(db);
    }
  }

  /**
   * Constructor - takes the context to allow the database to be opened/created.
   */
  public DbAdapter(Context context) {
    this.context = context;
  }

  /**
   * 
   *  
   * @return this (self reference, allowing this to be chained in an
   *         initialization call)
   */
  public DbAdapter open() {
    databaseHelper = new DatabaseHelper(context);
    database = databaseHelper.getWritableDatabase();
    return this;
  }

  /**
   * Closes the database.
   */
  public void close() {
    databaseHelper.close();
  }

  /**
   * Return true if database has been opened.
   */
  public boolean isOpen() {
    return database.isOpen();
  }

  /**
   * Deletes all elements.
   */
  public void deleteAllElements() {
    Logger.out("Deleting all elements from database");
    deleteAllElements(TABLE_SONGS);
  }

  /**
   * Deletes all elements of a certain table.
   */
  public boolean deleteAllElements(String table) {
    return database.delete(table, null, null) > 0;
  }

  /**
   * Adds a single song.
   */
  public boolean addSong(Song song) {
    ContentValues initialValues = new ContentValues();

    initialValues.put("uniqueID", song.uniqueId);

    // check whether that song already exists
    Cursor c = database.query(true, TABLE_SONGS, new String[] { KEY_ROWID }, "uniqueID" + "='"
        + song.uniqueId + "'", null, null, null, null, null);
    
    
    try {
      if (c != null) {
        c.moveToFirst();
        if (c.getCount() != 0) {
          return false;
        }
      }
    } finally {
      if (c != null) {
        c.close();
      }
    }
    return database.insert(TABLE_SONGS, null, initialValues) > 0;
  }

  /**
   * Adds each song in an array.
   */
  public void addSongs(Song[] songs) {
    int length = songs.length;
    for (int i = 0; i < length; i++) {
      addSong(songs[i]);
    }
  }

  /**
   * Returns a cursor to all the songs.
   */
  public Cursor getStarredSongCursor() {
    return database.query(TABLE_SONGS, null, null, null, null, null, null);
  }
  
  /**
   * Deletes a single song.
   */
  public int deleteSong(Song song) {
    return database.delete(TABLE_SONGS, "uniqueID='" + song.uniqueId + "'", null);
  }
}
